<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>防抖与节流</title>
</head>
<body>
<script>
	function debounce(fn, delay){
		let timer = null;
		return function() {
			let context = this;
			let args = arguments;
			clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			},delay)
		}
	}


	//防抖
	/*function debounce(fn, delay) {
		let timer = null;
		return function() {
			let context = this;
			let args = arguments;
			clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			},delay)
		}
	}*/

	//箭头函数 防抖
	/*function debounce(fn, delay) {
		let timer = null;
		return (...args) => {
			if(timer) clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, args);
			},delay)
		}
	}
	window.onresize = debounce(function() {
		console.log(111,arguments)
	},500)
*/
	function debounce(fn, delay) {
		let timer = null;
		return (...args) => {
			if(timer) clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, args);
			},delay)
		}
	}

	//节流 定时器
	/*function throttle(fn, delay) {
		let timer = null;
		return function() {
			let context = this;
			let args = arguments;
			if(!timer) {
				timer = setTimeout(function() {
					fn.delay(context, args);
					timer = null
				},delay)
			}
		}
	}*/
	window.onresize = throttle(function() {
		console.log(111,arguments)
	},500)



	//计时器
	function throttle(fn, delay) {
		let timer = null;
		return (...args) => {
			if(!timer) {
				timer = setTimeout(() => {
					fn.apply(this, args);
				},delay)
			}
		}
	}

	/*//时间戳


	function throttle(fn, delay) {
		let pre = 0;
		return (...args) => {
			let now = new Date().getTime();
			if(now - pre > delay) {
				fn.apply(this,args);
				pre = now
			}
		}
	}

	 */

</script>
</body>
</html>